package vip.liux.backend.infrastructure.jpa.customer;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import vip.liux.contracts.models.customer.Customer;
import vip.liux.contracts.repositories.customer.CustomerRepository;

import java.time.LocalDateTime;
import java.util.List;

public interface CustomerJpaRepository extends JpaRepository<Customer, Long>, CustomerRepository, JpaSpecificationExecutor<Customer> {

    default Page<Customer> findPageList(String search, LocalDateTime registerStartTime, LocalDateTime registerEndTime, Pageable page) {
        return findAll((root, query, criteriaBuilder) -> {
            var predicates = criteriaBuilder.conjunction();
            if (search != null && !search.isBlank()) {
                predicates = criteriaBuilder.and(predicates, criteriaBuilder.or(
                        criteriaBuilder.equal(root.get("uid"), search),
                        criteriaBuilder.like(root.get("username"), "%" + search + "%"),
                        criteriaBuilder.like(root.get("nickname"), "%" + search + "%"),
                        criteriaBuilder.like(root.get("mobile"), "%" + search + "%")
                ));
            }
            if (registerStartTime != null) {
                predicates = criteriaBuilder.and(predicates, criteriaBuilder.greaterThanOrEqualTo(root.get("creationTime"), registerStartTime));
            }
            if (registerEndTime != null) {
                predicates = criteriaBuilder.and(predicates, criteriaBuilder.lessThanOrEqualTo(root.get("creationTime"), registerEndTime));
            }
            return predicates;
        }, PageRequest.of(page.getPageNumber(), page.getPageSize()));
    }

    List<Customer> findByIdIn(List<Long> ids);
}